package com.weijia;

import javax.swing.*;
import java.util.*;
import java.util.concurrent.*;

public class GameManager {
    private GamePanel gamePanel;
    private ControlPanel controlPanel;
    private PauseOverlay pauseOverlay;
    private TypingGamePlus mainFrame;

    // 游戏状态
    private boolean gameRunning = false;
    private boolean gamePaused = false;
    private int score = 0;
    private int totalWords = 0;
    private int wordsTyped = 0;
    private int wordsMissed = 0;
    private TypingGamePlus.Difficulty difficulty = TypingGamePlus.Difficulty.NORMAL;

    // 单词管理
    private List<String> wordList = new ArrayList<>();
    private List<FallingWord> activeWords = new ArrayList<>();
    private Map<String, Integer> errorStats = new HashMap<>();

    // 线程管理
    private ScheduledExecutorService executor;
    private ScheduledFuture<?> spawnFuture;
    private ScheduledFuture<?> updateFuture;

    private int highScore = 0;
    private String highScoreDate = "";
    private final String HIGH_SCORE_FILE = "highscore.txt";

    public GameManager(GamePanel gamePanel, ControlPanel controlPanel, PauseOverlay pauseOverlay, TypingGamePlus mainFrame) {
        this.gamePanel = gamePanel;
        this.controlPanel = controlPanel;
        this.pauseOverlay = pauseOverlay;
        this.mainFrame = mainFrame;
        loadHighScore();
        initializeGame();
    }

    public void initializeGame() {
        // 初始示例文章
        String sampleText = "Java is a high-level, class-based, object-oriented programming language that is " +
                "designed to have as few implementation dependencies as possible. It is a general-purpose " +
                "programming language intended to let programmers write once, run anywhere, meaning that " +
                "compiled Java code can run on all platforms that support Java without the need for recompilation.";
        controlPanel.setArticleText(sampleText);
    }

    public void startGame() {
        if (wordList.isEmpty()) {
            JOptionPane.showMessageDialog(mainFrame, "请先加载文章！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        // 重置游戏状态
        gameRunning = true;
        gamePaused = false;
        score = 0;
        wordsTyped = 0;
        wordsMissed = 0;
        activeWords.clear();
        errorStats.clear();
        controlPanel.updateScore(score);
        controlPanel.updateRemainingWords(wordList.size());
        controlPanel.updateProgress(0);
        controlPanel.updateErrorStats("");
        controlPanel.updatePauseButtonText("暂停");
        pauseOverlay.setVisible(false);
        if (executor != null && !executor.isShutdown()) {
            executor.shutdownNow();
        }
        executor = Executors.newScheduledThreadPool(2);
        // 单词生成线程
        spawnFuture = executor.scheduleAtFixedRate(() -> {
            if (!gameRunning || gamePaused || wordList.isEmpty()) return;
            int index = new Random().nextInt(wordList.size());
            String word = wordList.get(index);
            wordList.remove(index);
            SwingUtilities.invokeLater(() -> {
                activeWords.add(new FallingWord(word, gamePanel.getWidth(), difficulty));
                controlPanel.updateRemainingWords(wordList.size());
            });
        }, 0, difficulty.getWordSpawnInterval(), TimeUnit.MILLISECONDS);
        // 游戏更新线程
        updateFuture = executor.scheduleAtFixedRate(() -> {
            if (!gameRunning || gamePaused) return;
            List<FallingWord> toRemove = new ArrayList<>();
            for (FallingWord fw : activeWords) {
                fw.y += fw.speed;
                if (fw.y > gamePanel.getHeight()) {
                    toRemove.add(fw);
                    wordsMissed++;
                    recordError(fw.word);
                }
            }
            activeWords.removeAll(toRemove);
            if (wordList.isEmpty() && activeWords.isEmpty()) {
                endGame();
            }
            SwingUtilities.invokeLater(() -> {
                gamePanel.repaint();
                int remaining = wordList.size() + activeWords.size();
                int progress = totalWords == 0 ? 0 : (int) ((double) (totalWords - remaining) / totalWords * 100);
                controlPanel.updateProgress(progress);
            });
        }, 0, 30, TimeUnit.MILLISECONDS);
    }

    public void pauseGame() {
        if (!gameRunning || gamePaused) return;
        gamePaused = true;
        controlPanel.updatePauseButtonText("继续");
        pauseOverlay.setVisible(true);
    }

    public void resumeGame() {
        if (!gameRunning || !gamePaused) return;
        gamePaused = false;
        controlPanel.updatePauseButtonText("暂停");
        pauseOverlay.setVisible(false);
    }

    public void restartGame() {
        if (executor != null && !executor.isShutdown()) {
            executor.shutdownNow();
        }
        gameRunning = false;
        gamePaused = false;
        // 重新分词并填充 wordList
        String text = controlPanel.getArticleText();
        List<String> newWordList = new ArrayList<>();
        String[] words = text.split("[\\s,.!?;:\"()]+");
        for (String word : words) {
            if (word.length() > 1) {
                newWordList.add(word);
            }
        }
        this.wordList = newWordList;
        this.totalWords = newWordList.size();
        if (!wordList.isEmpty()) {
            TypingGamePlus.Difficulty currentDifficulty = difficulty;
            activeWords.clear();
            errorStats.clear();
            score = 0;
            wordsTyped = 0;
            wordsMissed = 0;
            startGame();
            controlPanel.setDifficulty(currentDifficulty);
        } else {
            JOptionPane.showMessageDialog(mainFrame, "请先加载文章！", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }

    public void recordError(String word) {
        errorStats.put(word, errorStats.getOrDefault(word, 0) + 1);
        updateErrorDisplay();
    }

    public void updateErrorDisplay() {
        StringBuilder sb = new StringBuilder("错误单词统计:\n");
        for (Map.Entry<String, Integer> entry : errorStats.entrySet()) {
            sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("次\n");
        }
        controlPanel.updateErrorStats(sb.toString());
    }

    public void endGame() {
        gameRunning = false;
        gamePaused = false;
        if (executor != null) {
            executor.shutdown();
        }
        // 检查是否刷新最高分
        if (score > highScore) {
            highScore = score;
            highScoreDate = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm").format(new java.util.Date());
            saveHighScore();
            controlPanel.updateHighScore(highScore, highScoreDate);
        }
        StringBuilder report = new StringBuilder();
        report.append("游戏结束！\n\n");
        report.append("难度: ").append(
                difficulty.name().toLowerCase().replace("_", " ").substring(0, 1).toUpperCase()
                        + difficulty.name().toLowerCase().replace("_", " ").substring(1)
        ).append("\n");
        report.append("最终得分: ").append(score).append("\n");
        report.append("正确输入单词: ").append(wordsTyped).append("\n");
        report.append("未输入单词: ").append(wordsMissed).append("\n\n");
        report.append("错误单词分析:\n");
        for (Map.Entry<String, Integer> entry : errorStats.entrySet()) {
            report.append("- ").append(entry.getKey()).append(": ")
                    .append(entry.getValue()).append("次错误\n");
        }
        JOptionPane.showMessageDialog(mainFrame, report.toString(), "游戏结束", JOptionPane.INFORMATION_MESSAGE);
        controlPanel.updatePauseButtonText("暂停");
    }

    public void processInput(String input) {
        if (!gameRunning || gamePaused) return;
        if (input.isEmpty()) return;
        boolean wordTyped = false;
        Iterator<FallingWord> iterator = activeWords.iterator();
        while (iterator.hasNext()) {
            FallingWord fw = iterator.next();
            if (fw.word.equalsIgnoreCase(input)) {
                int points = fw.word.length() * 10 * (difficulty.ordinal() + 1);
                score += points;
                wordsTyped++;
                controlPanel.updateScore(score);
                iterator.remove();
                wordTyped = true;
                break;
            }
        }
        if (!wordTyped) {
            recordError(input);
        }
        controlPanel.clearInputField();
    }

    // 供 ControlPanel 调用
    public void setWordList(List<String> words) {
        this.wordList = words;
        this.totalWords = words.size();
    }
    public void setDifficulty(TypingGamePlus.Difficulty difficulty) {
        this.difficulty = difficulty;
    }
    public TypingGamePlus.Difficulty getDifficulty() {
        return this.difficulty;
    }
    public boolean isGameRunning() {
        return gameRunning;
    }
    public boolean isGamePaused() {
        return gamePaused;
    }
    public List<FallingWord> getActiveWords() {
        return activeWords;
    }
    public int getScore() {
        return score;
    }

    private void loadHighScore() {
        java.io.File file = new java.io.File(HIGH_SCORE_FILE);
        if (file.exists()) {
            try (java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.FileReader(file))) {
                String line = reader.readLine();
                if (line != null) {
                    String[] parts = line.split(",");
                    if (parts.length == 2) {
                        highScore = Integer.parseInt(parts[0]);
                        highScoreDate = parts[1];
                    }
                }
            } catch (Exception ignored) {}
        }
        controlPanel.updateHighScore(highScore, highScoreDate);
    }
    private void saveHighScore() {
        try (java.io.PrintWriter writer = new java.io.PrintWriter(HIGH_SCORE_FILE)) {
            writer.println(highScore + "," + highScoreDate);
        } catch (Exception ignored) {}
    }

    public void resetHighScore() {
        highScore = 0;
        highScoreDate = "";
        saveHighScore();
        controlPanel.updateHighScore(highScore, highScoreDate);
    }

    public void endGameNow() {
        if (executor != null) {
            executor.shutdownNow();
        }
        gameRunning = false;
        gamePaused = false;
        activeWords.clear();
        score = 0;
        wordsTyped = 0;
        wordsMissed = 0;
        errorStats.clear();
        // 重新分词并填充 wordList
        String text = controlPanel.getArticleText();
        List<String> newWordList = new ArrayList<>();
        String[] words = text.split("[\\s,.!?;:\"()]+");
        for (String word : words) {
            if (word.length() > 1) {
                newWordList.add(word);
            }
        }
        this.wordList = newWordList;
        this.totalWords = newWordList.size();
        controlPanel.updateScore(0);
        controlPanel.updateProgress(0);
        controlPanel.updateErrorStats("");
        controlPanel.updatePauseButtonText("暂停");
        controlPanel.updateRemainingWords(wordList.size());
        gamePanel.repaint();
        pauseOverlay.setVisible(false);
    }
} 